import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  message,
  Badge,
  Table,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './CodeList.less';

const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = {"[20]":'success', "[40]":'error'};
const status = {"[20]":'有效', "[40]":"无效"};
const type = {'[10]':'直接抵扣券', "[20]":"满减券","[30]":"折扣券","[40]":"活动推广码"};

// 创建状态select选择项
const stateChildren = [];
Object.keys(status).forEach( (key,index) => {
  stateChildren.push(<Option value={key} key={index}>{status[key]}</Option>);
});

// 创建类型select选择项
const typeChildren = [];
Object.keys(type).forEach( (key,index) => {
  typeChildren.push(<Option value={key} key={index}>{type[key]}</Option>);
});

// 新增邀请码
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新建邀请码"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: 'Please input some description...' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="码类型">
        {form.getFieldDecorator('cType', {
            rules: [{ required: true, message: 'Please input some description...' }],
          })(<Select placeholder="请选择" style={{ width: '100%' }}><Option key="1" value="40">活动推广码</Option></Select>)}
      </FormItem>
    </Modal>
  );
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()


export default class CodeList extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    state:"[20,40]",
    desc:null,
    cType:"[10,20,30,40]",
    pageNum:0,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { state,desc,cType,pageNum } = this.state;
    dispatch({
      type: 'rule/getPromoCodeList',
      payload: {state,desc,cType,pageNum},
    });
  }


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,state,desc,cType } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    this.setState({
      pageNum : pagination.current-1,
    });
    const params = {
      pageNum: pagination.current-1,
      pageSize: pagination.pageSize,
      ...formValues,
      state,
      desc,
      cType,
      filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rule/getPromoCodeList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      modalVisible: false,
      formValues: {},
      state:"[20,40]",
      desc:null,
      cType:"[10,20,30,40]",
      pageNum:0,
    });
    dispatch({
      type: 'rule/getPromoCodeList',
      payload: {
        state:"[20,40]",
        desc:null,
        cType:"[10,20,30,40]",
        pageNum:0,
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        desc: fieldsValue.desc,
        state: fieldsValue.state || "[20,40]",
        cType: fieldsValue.c_type || "[10,20,30,40]",
      });
      const { pageNum } = this.state;
      dispatch({
        type: 'rule/getPromoCodeList',
        payload: { state:fieldsValue.state,desc:fieldsValue.desc,cType:fieldsValue.c_type,pageNum },
      });
    });
  };


  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    this.setState({
      desc: null,
      state:  "[20,40]",
      cType: "[10,20,30,40]",
      pageNum:0,
    });
    dispatch({
      type: 'rule/createPromoCode',
      payload: {
        desc01: fields.desc,
        cType01:fields.cType,
        desc: null,
        state:  "[20,40]",
        cType: "[10,20,30,40]",
        pageNum:0,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  // 筛选条件
  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="邀请码类型">
              {getFieldDecorator('c_type')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {typeChildren}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('state')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {stateChildren}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="邀请码描述">
              {getFieldDecorator('desc')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      rule: { data },
      loading,
    } = this.props;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...data.pagination,
    };
    const { modalVisible } = this.state;

    const columns = [
      {
        title: '码id',
        dataIndex: 'c_id',
      },
      {
        title: '邀请码编号',
        dataIndex: 'c_code',
      },
      {
        title: '描述',
        dataIndex: 'desc',
      },
      {
        title: '类型',
        dataIndex: 'c_type_desc',
      },
      {
        title: '状态',
        dataIndex: 'state',
        render(val) {
          const stateVal = "["+val+"]";
          return <Badge status={statusMap[stateVal]} text={status[stateVal]} />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
      },
      {
        title: '截止时间',
        dataIndex: 'expiry_time',
      },
    ];


    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="我的邀请码">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
            </div>
            <Table
              loading={loading}
              dataSource={data.list}
              columns={columns}
              pagination={paginationProps}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderLayout>
    );
  }
}
